import logging

import pymysql

# 配置日志
logging.basicConfig(level=logging.ERROR)

class DatabaseUtil:
    conn = None
    cursor = None
    # 连接数据库
    @classmethod
    def get_conn(cls):
        if cls.conn is None:
            cls.conn = pymysql.connect(host='192.168.126.132',
                                   user='root',
                                   password='123456',
                                   database='litemall',
                                   port=3306,
                                   charset='utf8')
        return cls.conn

    # 获取游标对象
    @classmethod
    def get_cursor(cls):
        if cls.cursor is None:
            cls.cursor = cls.get_conn().cursor()
        return cls.cursor

    #执行sql语句
    @classmethod
    def exe_sql(cls,sql):
        try:
            cursor = cls.get_cursor()
            cursor.execute(sql)
            if sql.split()[0].upper() == 'SELECT':
                result = cursor.fetchall()
                return result
            else:
                cls.conn.commit()
                return cursor.rowcount
        except Exception as e:
            logging.error(f"操作数据库出错: {e}")
            print(e)
            cls.conn.rollback()
        finally:
            cls.close_cursor()
            cls.close_conn()


    # 释放游标
    @classmethod
    def close_cursor(cls):
        if cls.cursor:
            cls.cursor.close()
            cls.cursor = None

    # 释放连接
    @classmethod
    def close_conn(cls):
        if cls.conn:
            cls.conn.close()
            cls.conn = None


if __name__ == '__main__':
    db =  DatabaseUtil()
    print(db.exe_sql("select * from litemall_keyword"))
    print(db.exe_sql("update litemall_keyword set keywor = '父亲节' where id = 1;"))
    print(db.exe_sql("select * from litemall_keyword"))
